//标签过滤
function escapeStr(str) {
    // 初始化一个空字符串用于存储替换后的结果
    let result = '';
    // 遍历字符串中的每个字符
    for (let i = 0; i < str.length; i++) {
        switch (str[i]) {
            case '&':
                result += '&amp;';
                break;
            case '<':
                result += '&lt;';
                break;
            case '>':
                result += '&gt;';
                break;
            case '"':
                result += '&quot;';
                break;
            case "'":
                result += '&#039;';
                break;
            default:
                // 如果不是特殊字符，直接添加到结果字符串中
                result += str[i];
        }
    }
    return result;
}

const allInputs = document.querySelectorAll('input[type="text"]');
allInputs.forEach((input) => {
    input.addEventListener('change', function () {
        input.value = escapeStr(input.value);
    })
})
document.getElementById('top_bar_search').value = '';
//封装alert弹窗
const alertBox = document.querySelector('.alert');
function showAlert(message,color) {
    alertBox.textContent = message;
    alertBox.style.color = color;
    alertBox.style.display = 'block';
    setTimeout(() => {
        alertBox.style.display = 'none';
    }, 3000);
}
const fans = document.getElementsByClassName("fans")[0];
const attention = document.getElementsByClassName("attention")[0];
const showModal_fa = document.getElementsByClassName("showModal_fa")[0];
const tc_fans_attention = document.getElementsByClassName("tc-fans-attention")[0];
const fans_list_btn = document.getElementsByClassName("fans_list_btn")[0];
const attention_list_btn = document.getElementsByClassName("attention_list_btn")[0];
const fans_list = document.getElementsByClassName("fans_list")[0];
const attention_list = document.getElementsByClassName("attention_list")[0];
const close_fansORattention = document.getElementById("close_fansORattention");
const more_message = document.getElementById("more_message");
const showModal = document.getElementById("showModal");
const personal_message_tc_box = document.getElementById("personal_message_tc_box");
const close_personalMessage = document.getElementById("close_personalMessage");
const close_personalMessage2 = document.getElementsByClassName("close_personalMessage2")[0];

//封装二级菜单
function dropdown(enterE, dropE) {
    let timer;
    enterE.addEventListener("mouseenter", () => {
        clearTimeout(timer);
        dropE.style.display = "block";
        dropE.style.opacity = '1';
        dropE.style.transform = 'translateY(0)';
    });
    enterE.addEventListener("mouseleave", () => {
        dropE.style.opacity = '0';
        dropE.style.transform = 'translateY(-10px)';
        timer = setTimeout(() => {
            dropE.style.display = "none";
        }, 300);
    });
    return timer;
}

// 顶栏二级菜单
const news_dropdown = document.querySelector('.news_dropdown');
const top_bar_news = document.querySelector('.top_bar_news');
const publish_dropdown = document.querySelector('.publish_dropdown');
const top_bar_publish = document.querySelector('.top_bar_publish');
const personalDropdown = document.querySelector('.personal_dropdown');
const topBarPersonal = document.querySelector(".top_bar_personal");
let timer_news = dropdown(top_bar_news, news_dropdown);
let timer_publish = dropdown(top_bar_publish, publish_dropdown);
dropdown(topBarPersonal, personalDropdown);

//顶栏二级菜单内容点击后页面跳转
const newsJump = news_dropdown.getElementsByTagName('li');
newsJump[0].onclick = function () {
    window.location.href = "mainPage.html"
}

//粉丝/关注列表
const fansList = document.getElementsByClassName("fans_list")[0];
const attentionList = document.getElementsByClassName("attention_list")[0];
let fanPageNum=1;
let attentionPageNum=1;
function getMoreAttFun(){
    const getMoreAtt = document.getElementById("getMoreAtt");
    if(getMoreAtt)getMoreAtt.onclick=( function (e) {
        $.ajax({
            url: `/user/followedList?pageNum=${attentionPageNum}`,
            type: "get",
            dataType: "json",
            contentType: "application/json",
            success: (data) => {
                fanPageNum++;
                getMoreAtt.remove();
                for (let i = 0; i < data.data.followedList.length; i++) {
                    attentionList.innerHTML += `
                                    <div class="fans-card">
                                        <a href="/redirectToPage/${data.data.followedList[i].userId}" class="jump-fans-page" target="_blank">
                                            <div class="fan-avatar-div">
                                                <img alt="头像" class="fans-avatar" src="${data.data.followedList[i].avatar}">
                                            </div>
                                            <div class="fans-info">
                                                <span class="fans-name" >${data.data.followedList[i].userName}</span>
                                                <p class="fans-info-f">${data.data.followedList[i].followerCount + '粉丝·' + (data.data.followedList[i].verContent == "暂未获得认证" ? '未认证' :data.data.followedList[i].verContent )}</p>
                                            </div>
                                        </a>
                                       ${data.data.followedList[i].followed?'<button class="follow-btn"><span>已关注</span></button>':'<button class="follow-btn" style="background-color: ##f04142"><span>关注</span></button>'}
                                    </div>
                                `;
                }
                attentionList.innerHTML +=!data.data.hasMore?'<p id="hasNoneatt" class="hasNone">以显示全部关注用户</p>':'<button type="button" class="more-user" id="getMoreAtt"><p class="moreP">查看更多关注</p>></button>';
                getMoreAttFun();
            }
        })
    })
}
function getMoreFanFun(){
    const getMoreFan = document.getElementById("getMoreFan");
    if(getMoreFan)getMoreFan.onclick=( function (e) {
        $.ajax({
            url: `/user/followerList?pageNum=${fanPageNum}`,
            type: "get",
            dataType: "json",
            contentType: "application/json",
            success: (data) => {
                fanPageNum++;
                getMoreFan.remove();
                for (let i = 0; i < data.data.followers.length; i++) {
                    fansList.innerHTML += `
                                    <div class="fans-card">
                                        <a href="/redirectToPage/${data.data.followers[i].userId}" class="jump-fans-page" target="_blank">
                                            <div class="fan-avatar-div">
                                                <img alt="头像" class="fans-avatar" src="${data.data.followers[i].avatar}">
                                            </div>
                                            <div class="fans-info">
                                                <span class="fans-name" >${data.data.followers[i].userName}</span>
                                                <p class="fans-info-f">${data.data.followers[i].followerCount + '粉丝·' + (data.data.followers[i].verContent == "暂未获得认证" ? '未认证' :data.data.followers[i].verContent )}</p>
                                            </div>
                                        </a>
                                        ${data.data.followers[i].followed ?'<button class="follow-btn"><span>已关注</span></button>':'<button class="follow-btn" style="background-color: ##f04142"><span>关注</span></button>'}
                                        <button class="follow-btn"><span>已关注</span></button>
                                    </div>
                                `;
                }
                fansList.innerHTML +=!data.data.hasMore?'<p id="hasNonefan" class="hasNone">以显示全部粉丝用户</p>':'<button type="button" class="more-user" id="getMoreFan"><p class="moreP">查看更多粉丝</p>></button>';
                getMoreFanFun();
            }
        })
    })
}
function tc_f_a(fanORatt) {
    tc_fans_attention.style.width = "440px";
    // 共用的关注/取消关注处理函数
    function handleFollowButtonClick(userId, button) {
        const followCount1=document.getElementsByClassName('attention')[0].getElementsByTagName('span')[0];
        const followCoun2=document.getElementsByClassName('attention_list_btn')[0].getElementsByTagName('span')[0];
        $.ajax({
            url: `/NewsController/follow?followedId=${userId}`,
            type: "post",
            dataType: "json",
            contentType: "application/json",
            success: (data) => {
                if (data.message === "取消关注") {
                    button.innerHTML = '<span>关注</span>';
                    button.style.backgroundColor = '#f04142';
                    button.style.color = 'white';
                    followCount1.innerHTML=parseInt(followCount1.innerHTML)-1+'';
                    followCoun2.innerHTML=parseInt(followCoun2.innerHTML)-1+'';
                } else {
                    button.innerHTML = '<span>已关注</span>';
                    button.style.backgroundColor = '';
                    button.style.color = '';
                    followCount1.innerHTML=parseInt(followCount1.innerHTML)+1+'';
                    followCoun2.innerHTML=parseInt(followCoun2.innerHTML)+1+'';
                }
            },
            error: (data) => {
                showAlert("请求超时，请稍后再试", "red");
            }
        });
    }
    // 处理粉丝列表
    if (fanORatt === "fan") {
        fanPageNum = 1;
        $.ajax({
            url: `/user/followerList?pageNum=${fanPageNum}`,
            type: "get",
            dataType: "json",
            contentType: "application/json",
            success: (data) => {
                fansList.innerHTML = "";
                fanPageNum++;
                if (data.data.followers.length === 0) {
                    fansList.innerHTML = "<p style='text-align: center;'>暂无粉丝</p>";
                } else {
                    // 创建粉丝列表 HTML
                    const html = data.data.followers.map(follower => `
                        <div class="fans-card">
                            <a href="/redirectToPage/${follower.userId}" class="jump-fans-page" target="_blank">
                                <div class="fan-avatar-div">
                                    <img alt="头像" class="fans-avatar" src="${follower.avatar}">
                                </div>
                                <div class="fans-info">
                                    <span class="fans-name">${follower.userName}</span>
                                    <p class="fans-info-f">${follower.followerCount===null?0+'粉丝·' + (follower.verContent === "暂未获得认证" ? '未认证' : follower.verContent):follower.followerCount + '粉丝·' + (follower.verContent === "暂未获得认证" ? '未认证' : follower.verContent)}</p>
                                </div>
                            </a>
                            <button class="follow-btn" data-user-id="${follower.userId}" ${follower.followed ? '' : 'style="background-color: #f04142;color:white;"'}>
                                <span>${follower.followed ? '已关注' : '关注'}</span>
                            </button>
                        </div>
                    `).join('');
                    fansList.innerHTML = html;
                    // 使用事件委托绑定事件
                    fansList.addEventListener('click', (e) => {
                        if (e.target.closest('.follow-btn')) {
                            const button = e.target.closest('.follow-btn');
                            const userId = button.getAttribute('data-user-id');
                            handleFollowButtonClick(userId, button);
                        }
                    });
                }
                fansList.innerHTML += !data.data.hasMore
                    ? '<p id="hasNonefan" class="hasNone">已显示全部粉丝用户</p>'
                    : '<button type="button" class="more-user" id="getMoreFan"><p class="moreP">查看更多粉丝</p>></button>';
                getMoreFanFun();
            },
            error: (err) => {
                fansList.innerHTML = "";
                fansList.innerHTML = "<p style='text-align: center;'>暂无粉丝</p>";
            }
        });
        fans_list_btn.classList.add("FA_active");
        attention_list_btn.classList.remove("FA_active");
        showModal_fa.style.display = "block";
        fans_list.style.display = "block";
        attention_list.style.display = "none";
    }
    // 处理关注列表
    else {
        attentionPageNum = 1;
        $.ajax({
            url: `/user/followedList?pageNum=${attentionPageNum}`,
            type: "get",
            dataType: "json",
            contentType: "application/json",
            success: (data) => {
                attentionList.innerHTML = "";
                attentionPageNum++;
                if (data.data.followedList.length === 0) {
                    attentionList.innerHTML = "<p style='text-align: center;'>暂无关注</p>";
                } else {
                    // 创建关注列表 HTML
                    const html = data.data.followedList.map(followed => `
                        <div class="fans-card">
                            <a href="/redirectToPage/${followed.userId}" class="jump-fans-page" target="_blank">
                                <div class="fan-avatar-div">
                                    <img alt="头像" class="fans-avatar" src="${followed.avatar}">
                                </div>
                                <div class="fans-info">
                                    <span class="fans-name">${followed.userName}</span>
                                    <p class="fans-info-f">${followed.followerCount===null?0+ '粉丝·' + (followed.verContent === "暂未获得认证" ? '未认证' : followed.verContent):followed.followerCount + '粉丝·' + (followed.verContent === "暂未获得认证" ? '未认证' : followed.verContent)}</p>
                                </div>
                            </a>
                            <button class="follow-btn" data-user-id="${followed.userId}" ${followed.followed ? '' : 'style="background-color: #f04142;color:white;"'}>
                                <span>${followed.followed ? '已关注' : '关注'}</span>
                            </button>
                        </div>
                    `).join('');
                    attentionList.innerHTML = html;
                    // 使用事件委托绑定事件
                    attentionList.addEventListener('click', (e) => {
                        if (e.target.closest('.follow-btn')) {
                            const button = e.target.closest('.follow-btn');
                            const userId = button.getAttribute('data-user-id');
                            handleFollowButtonClick(userId, button);
                        }
                    });
                }
                attentionList.innerHTML += !data.data.hasMore
                    ? '<p id="hasNoneatt" class="hasNone">已显示全部关注用户</p>'
                    : '<button type="button" class="more-user" id="getMoreAtt"><p class="moreP">查看更多关注</p>></button>';
                getMoreAttFun();
            },
            error: (err) => {
                attentionList.innerHTML = "";
                attentionList.innerHTML = "<p style='text-align: center;'>暂无关注</p>";
            }
        });
        fans_list_btn.classList.remove("FA_active");
        attention_list_btn.classList.add("FA_active");
        fans_list.style.display = "none";
        showModal_fa.style.display = "block";
        attention_list.style.display = "block";
    }
}

showModal_fa.onclick = function () {
    tc_fans_attention.style.width = "0";
    showModal_fa.style.display = "none";
}
fans.addEventListener("click", () => tc_f_a("fan"), false);
attention.addEventListener("click", () => tc_f_a("attention"), false);
fans_list_btn.addEventListener("click", () => tc_f_a("fan"), false);
attention_list_btn.addEventListener("click", () => tc_f_a("attention"), false);
close_fansORattention.onclick = function () {
    tc_fans_attention.style.width = "0";
    showModal_fa.style.display = "none";
}

//弹窗封装
function tc_open(target_tc) {
    showModal.style.display = "block";
    target_tc.style.display = "block";
    setTimeout(() => {
        target_tc.style.scale = "1";
    }, 10)
}

function tc_close(target_tc) {
    target_tc.style.scale = "0";
    setTimeout(() => {
        showModal.style.display = "none";
        target_tc.style.display = "none";
    }, 100);
}

function tc_open2(targetTc, showM, flexOrblock) {
    showM.style.display = "block";
    targetTc.style.display = "" + flexOrblock;
    setTimeout(() => {
        targetTc.style.transform = "scale(1)";
    }, 10);
}

function tc_close2(targetTc, showM) {
    targetTc.style.transform = "scale(0)";
    setTimeout(() => {
        showM.style.display = "none";
        targetTc.style.display = "none";
    }, 100);
}

//个人资料查看弹窗
more_message.onclick = function () {
    tc_open(personal_message_tc_box);
}
close_personalMessage.addEventListener("click", () => tc_close(personal_message_tc_box), false);
close_personalMessage2.addEventListener("click", () => tc_close(personal_message_tc_box), false);
showModal.addEventListener("click", () => {
    tc_close(personal_message_tc_box);
}, false);

//个人主页文章、收藏等内容导航栏的样式切换
const my_titles = document.getElementsByClassName("my_titles");
const search_my_cancel = document.getElementById("search_my_cancel");
const search_my_box = document.getElementsByClassName("search_my_box")[0];
const my_message_title = document.getElementsByClassName("my_message_title")[0];
const search_my = document.getElementsByClassName("search_my")[0];
const classIdMap = {
    article: 1,
    microheadline: 2,
    collection: 3
};
for (let nowT of my_titles) {
    nowT.addEventListener("click", function () {
        // 移除所有元素的 active_mmt 类
        for (let T of my_titles) {
            T.classList.remove("active_mmt");
        }
        // 给当前点击元素添加 active_mmt 类
        nowT.classList.add("active_mmt");
        let articleClass = nowT.dataset.class;
        getMyNews(articleClass);
    }, false)
}
let pagenum=1;

function getMyNews(articleClass) {                      //用于根据选择的分类获取内容
    const classId = classIdMap[articleClass];
    document.querySelector('.main_content').addEventListener('click', (e) => {
        if (e.target.id === 'getMoreArticle') { // 匹配按钮 ID
            getMoreArticlefun(classId); // 加载更多的函数
        }
    });
    pagenum=1;
    let url;
    if (classId === 1 || classId === 2) {
        url = `/selectUserPost/${classId}?pageNum=${pagenum}&userId=${window.user.userId}`;
    } else if (classId === 3) {
        // 修正 URL
        url = `/selectPostById/${window.user.userId}?pageNum=${pagenum}`;
    }
    if (url) {
        $.ajax({
            url,
            type: 'GET',
            dataType: "json",
            contentType: "application/json",
            success: function (response) {
                // 合并更新内容函数
                pagenum++;
                if(response.data==null){
                    updateContent([],[],classId);
                }else updateContent(response.data.posts,response,classId);
            },
            error: function (error) {
                showAlert("获取内容失败", "red");
            }
        })
    }
}
//为文章内容添加点击事件
function getMoreArticlefun(classId) {
    const getMoreArticle = document.getElementById("getMoreArticle");
    const mainContent = document.getElementsByClassName("main_content")[0];
    if(getMoreArticle) {
        getMoreArticle.onclick= function (e) {
            let url;
            if (classId === 1 || classId === 2) {
                url = `/selectUserPost/${classId}?pageNum=${pagenum}&userId=${window.user.userId}`;
            } else if (classId === 3) {
                // 修正 URL
                url = `/selectPostById/${window.user.userId}?pageNum=${pagenum}`;
            }
            $.ajax({
                url: url,
                type: "get",
                dataType: "json",
                contentType: "application/json",
                success: (data) => {
                    pagenum++;
                    getMoreArticle.remove();
                    for (let i = 0; i < data.data.posts.length; i++) {
                        mainContent.innerHTML += `
                            <div class="news-contents">
                                <div class="feed-card">
                                    <a class="title" href="/NewsController/${data.data.posts[i].postId}">${data.data.posts[i].title}</a>
                                    <div class="feed-card-bottom">
                                        <span class="comments-num" >${data.data.posts[i].commentCount}评论</span>
                                        <span class="post-date">${data.data.posts[i].createdTime}</span>
                                    </div>
                                </div>
                                <div class="news-image">
                                    <a href="/NewsController/${data.data.posts[i].postId}" target="_blank" rel="noopener"
                                       title="${data.data.posts[i].title}" aria-hidden="false" tabIndex="0">
                                        <img src="${data.data.posts[i].coverImage}" alt="" alt="${data.data.posts[i].title}"/>
                                    </a>
                                </div>
                            </div>
                        `;
                    }
                    mainContent.innerHTML +=!data.data.hasMore?'<p id="hasNoneatt" class="hasNone hasNone1">以显示全部文章</p>':'<button type="button" class="more-user" id="getMoreArticle"><p class="moreP">查看更多</p>></button>';
                    getMoreArticlefun(classId);
                },
                error: (err) => {
                    showAlert("获取内容失败", "red");
                }
            })
        }
    }
}
function updateContent(result,response,classId) {        //用于更新文章内容
    let contentNumber = result.length;
    const mainContent = document.getElementsByClassName("main_content")[0];
    mainContent.innerHTML = "";
    if(contentNumber === 0) {
        mainContent.innerHTML = `<div class="without-content">
                                    <i class="iconfont icon-zanwuneirong without-content-img"></i>          <!--当没有内容时展示该内容-->
                                    <span class="without-content-text">暂无内容</span>
                                </div>`;
    }else{
        for(let i = 0; i < contentNumber; i++) {
            mainContent.innerHTML+=`
            <div class="news-contents">
                <div class="feed-card">
                    <a class="title" href="/NewsController/${result[i].postId}">${result[i].title}</a>
                    <div class="feed-card-bottom">
                        <span class="comments-num" >${result[i].commentCount}评论</span>
                        <span class="post-date">${result[i].createdTime}</span>
                    </div>
                </div>
                <div class="news-image">
                    <a href="/NewsController/${result[i].postId}" target="_blank" rel="noopener"
                       title="${result[i].title}" aria-hidden="false" tabIndex="0">
                        <img src="${result[i].coverImage}" alt="" alt="${result[i].title}"/>
                    </a>
                </div>
            </div>`
        }
        mainContent.innerHTML +=!response.data.hasMore?'<p id="hasNoneatt" class="hasNone hasNone1">以显示全部文章</p>':'<button type="button" class="more-user" id="getMoreArticle"><p class="moreP">查看更多</p>></button>';
        getMoreArticlefun(classId);
    }
}

search_my.addEventListener("click", () => {
    search_my_box.style.display = "flex"
    my_message_title.style.display = "none";
}, false);
search_my_cancel.addEventListener("click", () => {
    my_message_title.style.display = "flex"
    search_my_box.style.display = "none";
}, false);

// 设置个人资料的弹窗
const showModaluser = document.getElementById("showModal-set");      //设置弹窗的开关样式设置
const userSetTc = document.getElementById("user-setting-tc");
const userSet = document.getElementById("setting_inf");
const confirmSetuser = document.getElementById("confirm-user-set");
const cancelSetuser = document.getElementById("cancel-user-set");

userSet.addEventListener("click", () => {              //几个按钮的设置
    openUpdata();
    tc_open2(userSetTc, showModaluser, "flex");
    startProfile = userProfileImg.style.backgroundImage.replace(/url\(['"]?([^'"]+)['"]?\)/, '$1');
}, false);
[showModaluser, cancelSetuser].forEach((c) => {
    c.addEventListener("click", () => {
        userProfileImg.style.backgroundImage = `url(${startProfile})`;
        apf.value = '';         //取消修改时设置头像value为空
        clearInput();
        restoreStyle();
        tc_close2(userSetTc, showModaluser);
    }, false);
})
confirmSetuser.addEventListener('click', () => {
    clearInput();
    restoreStyle();
    //处理信息部分
    updatauserdata();
}, false);

function updatauserdata() {                                                 //在点击确认后更新用户信息(静态)
    const genders = document.querySelectorAll(".user-sex");
    let newName = document.getElementById("user-name-s").value;
    let newgender = genders[0].checked ? 0 : 1;
    let newProfile = '';
    if (userProfileImg && userProfileImg.style.backgroundImage) {
        const matchResult = userProfileImg.style.backgroundImage.match(/url\(['"]?([^'"]+)['"]?\)/);
        if (matchResult) {
            newProfile = matchResult[1];
        }
    }
    let newintroduction = document.getElementById("user-introduce").value;
    let newAddress = document.getElementById("user-address").value;
    updatauserdataAjax(
        newAddress,newProfile,newgender,newintroduction,newName
    );
}
function updatauserdataAjax(address, avatar, gender, introduction, userName) {
    let userdata = JSON.stringify({
        "address": address,
        "avatar": avatar,
        "gender": gender,
        "introduction": introduction,
        "userName": userName
    })
    $.ajax({
        url: "/user/updateUser",
        type: "post",
        dataType: "json",
        contentType: "application/json",
        data: userdata,
        success: function (response) {
            const name1 = document.getElementById("user_name");
            const name2 = document.getElementsByClassName("user_name_p")[0];
            const name3 = document.getElementById("user-name");
            const profiles = document.querySelectorAll(".profiles");
            const displayAddress = document.querySelector(".user_adress_p ");
            name1.innerHTML = userName;
            name3.innerHTML = userName;
            name2.innerHTML = `昵称：${userName}`;
            displayAddress.innerHTML = address;
            const briefIntroduce = document.getElementsByClassName("brief_introduction_u")[0];
            briefIntroduce.innerHTML = "简介：" + introduction;
            profiles.forEach((profile) => {
                const imageUrl = userProfileImg.style.backgroundImage.replace(/url\(['"]?([^'"]+)['"]?\)/, '$1');
                profile.src = imageUrl;
                profile.onerror = () => {
                    console.error('图片加载失败:', imageUrl);
                    // 可以在这里添加更多的错误处理逻辑，比如显示默认图片
                };
            });
            showAlert("修改成功","green");
            tc_close2(userSetTc, showModaluser);
        },
        error: function (error) {
            userProfileImg.style.backgroundImage = `url(${startProfile})`;
            document.getElementById("user-name-s").value=document.getElementById("user-name").innerHTML;
            apf.value = '';
            showAlert("修改失败","red");
        }
    });
}

const userSetName = document.getElementById("user-set-name");             //修改昵称
const confirmuserName = document.getElementById("confirm-user-name");
const userSetNamed1 = document.getElementById("user-name-d");
const userSetNamed2 = document.getElementById("user-name-d2");
const userName = document.getElementById("user-name");
const userNameS = document.getElementById("user-name-s");
userSetName.addEventListener('click', () => {
    userSetNamed1.style.display = "none";
    userSetNamed2.style.display = "inline-block";
}, false);
confirmuserName.addEventListener('click', () => {
    userSetNamed2.style.display = "none";
    userSetNamed1.style.display = "inline-block";
    userName.innerHTML = userNameS.value;
}, false);

const userProfileSet = document.getElementById("user-profile-shade");         //修改头像
const apf = document.getElementById("user-profile-file");
const userProfileImg = document.getElementById("user-profile");
let startProfile;
userProfileSet.addEventListener("click", () => {
    apf.click();
}, false)
apf.addEventListener("change", () => {
    const file = apf.files[0];
    if (file) {
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
            userProfileImg.style.backgroundImage = `url(${e.target.result})`;
        };
    }
}, false);

const toSetData = document.getElementById("to-set-data");
const toSetPrivacy = document.getElementById("to-set-privacy");
const usersetop = document.querySelectorAll(".user-set-op");
const tosetdp = document.querySelectorAll(".to-setdp");
[toSetData, toSetPrivacy].forEach((nowSet) => {
    nowSet.addEventListener("click", () => {
        const targetId = nowSet.dataset.target;
        const target_obj = document.getElementById(targetId);
        tosetdp.forEach((a) => a.classList.remove("active-sdp"));
        nowSet.classList.add("active-sdp");
        usersetop.forEach((m) => m.style.display = "none");
        target_obj.style.display = "block";
    })
});

const changePassword = document.getElementById("change-password");      //更改密码
const confirmChangePassword = document.getElementById("confirm-change-password");
const userPasswordBox = document.getElementById("user-password-d1");
const usernewPbox = document.getElementById("user-password-d2");
const usercode = document.getElementById("user-code");
changePassword.addEventListener("click", () => {
    userPasswordBox.style.display = "none";
    usernewPbox.style.display = "block";
});
confirmChangePassword.addEventListener("click", () => {
    if (judge()) return;
    const userPassword = document.getElementById("user-newpassword").value;
    const userCode = document.getElementById("user-code").value;
    $.ajax({
        url:`/user/updatePassword?code=${userCode}&email=${window.user.email.replace("@","%40")}&password=${userPassword}`,
        type: "post",
        dataType: "json",
        contentType: "application/json",
        success: function (response) {
            if(response.message==="验证码错误"){
                showAlert("验证码错误","red");
                return;
            }
            usernewPbox.style.display = "none";
            userPasswordBox.style.display = "block";
            clearInput();
            showAlert("修改成功！","green");
        },
        error: function () {
            clearInput();
            showAlert("修改失败！","red");
        }
    })
})
//更改密码时的密码验证
const newuserPassword = document.getElementById("user-newpassword");          //更改密码-小眼睛
const newuserPasswordT = document.getElementById("user-newpasswordT");
const passwordPrompt = document.querySelectorAll(".error-message");        //密码更改时的提示信息
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,64}$/;

function showPrompt(showObj) {
    showObj.style.display = "block";
}

function hiddenPrompt(hiddenObj) {
    hiddenObj.style.display = "none";
}

function judge() {       //判断密码是否可以进行更改
    let sta = true;
    if (newuserPassword.value === "" || !passwordRegex.test(newuserPassword.value)) {
        showPrompt(passwordPrompt[0]);
        sta = false;
    }
    // 比较输入框的值
    if (newuserPassword.value !== newuserPasswordT.value) {
        showPrompt(passwordPrompt[1]);
        sta = false;
    }
    if (usercode.value === "") {
        showPrompt(passwordPrompt[2]);
        sta = false;
    }
    return !sta;
}
newuserPassword.addEventListener("input", () => {
    const trimmedPassword = newuserPassword.value.trim(); // 去除首尾空格
    const isValid = passwordRegex.test(trimmedPassword);
    if (isValid) {
        hiddenPrompt(passwordPrompt[0]);
    } else {
        showPrompt(passwordPrompt[0]);
    }
});
newuserPasswordT.addEventListener("input", () => {
    // 比较输入框的值
    if (newuserPassword.value === newuserPasswordT.value) hiddenPrompt(passwordPrompt[1]);
})
usercode.addEventListener("input", () => {
    if (usercode.value !== "") hiddenPrompt(passwordPrompt[2]);
})
const passwordEye1 = document.getElementById('new-password-eye1');
const passwordEye2 = document.getElementById("new-password-eye2");

function showpassword(eye, passwordinp) {
    if (eye.classList.contains('icon-bukejian')) {
        eye.classList.replace('icon-bukejian', 'icon-kejian');
        passwordinp.type = "text";
    } else {
        eye.classList.replace('icon-kejian', 'icon-bukejian');
        passwordinp.type = "password";
    }
}

passwordEye1.addEventListener("click", () => {
    showpassword(passwordEye1, newuserPassword);
}, false);
passwordEye2.addEventListener("click", () => {
    showpassword(passwordEye2, newuserPasswordT);
}, false);

//发送验证码-更改密码
const sendCode = document.getElementById("send-code");
const COUNTDOWN = 60;     //发送验证码倒计时时间
var Countdown;
var timer;              //记录验证码定时器，防止多个定时器同时存在
function restoryCoundown() {         //用来获取验证码倒计时，防止页面刷新时倒计时清零
    var Sendtime = localStorage.getItem('Sendtime') - 0;
    var endtime = localStorage.getItem('endtime') - 0;
    if (Sendtime && endtime) {
        var nowtime = Date.now();
        if (nowtime >= endtime) {
            localStorage.removeItem('Sendtime');
            localStorage.removeItem('endtime');
        } else {
            clearInterval(timer);               //如果倒计时还没有结束，那么发送验证码的按钮仍然处于倒计时无法再次发送
            sendCode.disabled = true;
            Countdown = Math.floor((endtime - nowtime) / 1000);
            timer = setInterval(updateCountdown, 1000);
        }
    } else {
        Countdown = COUNTDOWN;
    }
}

restoryCoundown();      //调用用来判断是否倒计时还存在，如果存在则显示倒计时
function updateCountdown() {         //用来更新倒计时显示
    if (Countdown === 0) {
        sendCode.disabled = false;
        sendCode.innerText = "获取验证码";
        clearInterval(timer);
    } else {
        sendCode.innerText = Countdown;
        Countdown--;
    }
}
sendCode.onclick = function () {
    //发送验证码的操作
    sendCode.addEventListener("click",()=>{
        let SendTime = Date.now();                 //倒计时开始时的时间戳
        let endTime = SendTime + COUNTDOWN * 1000;   //倒计时结束时的时间戳
        localStorage.setItem('Sendtime', SendTime + '');     //保存数据到本地里面，便于重新加载页面时验证码倒计时的重新计算
        localStorage.setItem('endtime', endTime + '');
        Countdown = COUNTDOWN;
        sendCode.innerText = Countdown;
        sendCode.disabled = true;
        timer = setInterval(updateCountdown, 1000);
        $.ajax({
            url: `sendCodeToForgetPassword?email=${window.user.email.replace("@","%40")}`,
            dataType: "json",
            type: "get",
            contentType: "application/json",
            success: function (res) {
                showAlert("发送成功","green");
            },
            error: function () {
                showAlert("发送失败","red");
                // 清除倒计时
                clearInterval(timer);
                // 重置按钮状态
                sendCode.disabled = false;
                sendCode.innerText = "获取验证码";
                // 移除本地存储的倒计时信息
                localStorage.removeItem('Sendtime');
                localStorage.removeItem('endtime');
            }
        })
    })
}

//顶部栏搜索部分
const topBarSearch =  document.getElementById('top_bar_search');
const topBarSearchBtn = document.getElementsByClassName('search_button')[0];
topBarSearchBtn.addEventListener('click', () => {
    const searchContent = topBarSearch.value;
    if(searchContent===""){
        window.location.href = "*";
    }else{
        window.location.href = `/SearchController/search?searchString=${searchContent}`;
    }
})
const searchMynew = document.getElementsByClassName('search_my_input')[0];
const searchMyBtn = document.getElementById('search_my_confirm');
searchMyBtn.addEventListener('click', () => {
    const searchContent = searchMynew.value;
    if(searchContent===""){
        window.location.href = "*";
    }else{
        window.location.href = `/SearchController/search?searchString=${searchContent}`;
    }
})

//信息小红点部分
const redPoint = document.getElementsByClassName('red_point');
$.ajax({
    url: "/GetAnnouncementController/count",
    type: "get",
    dataType: "json",
    contentType: "application/json",
    success: function (response) {
        if(response===0){
            redPoint[0].style.display = "none";
        }else{
            if(response>=99) redPoint[0].innerHTML = '99+';
            else redPoint[0].innerHTML = response;
            redPoint[0].style.display = "block";
        }
    },
    error: function (error) {
        redPoint[0].style.display = "none";
    }
})

//当点击关闭时部分样式刷新
function openUpdata() {      //设置弹窗打开时进行部分数据的更新
    newuserPassword.value = "";
    newuserPasswordT.value = "";
    const gender = document.getElementsByClassName("user_gender_p div_p")[0].innerHTML;
    if (gender == "性别：男") {
        document.getElementsByClassName("user-sex")[0].checked = true;
    } else {
        document.getElementsByClassName("user-sex")[1].checked = true;
    }
}

function clearInput() {
    newuserPassword.value = "";
    newuserPasswordT.value = "";
    document.getElementById("user-code").value = "";
    if (document.getElementsByClassName("user-sex")[0].checked) {
        document.getElementsByClassName("user_gender_p div_p")[0].innerHTML = "性别：男";
        //性别改变
    } else {
        document.getElementsByClassName("user_gender_p div_p")[0].innerHTML = "性别：女";
    }
}

function restoreStyle() {
    [toSetData, toSetPrivacy].forEach(() => {
        tosetdp.forEach((a) => a.classList.remove("active-sdp"));
        toSetData.classList.add("active-sdp");
        document.getElementById("user-data-set").style.display = "block";
        document.getElementById('user-privacy-set').style.display = "none";
    });
    userSetNamed2.style.display = "none";
    userSetNamed1.style.display = "inline-block";
    usernewPbox.style.display = "none";
    userPasswordBox.style.display = "block";
}

//页面跳转部分设置
function jump(href) {
    window.location.href = href;
}
//顶部导航栏处跳转
const messages = news_dropdown.getElementsByTagName("li");
for (let message of messages) {
    message.onclick = function () {
        jump("/creator")
    };
}
const publishs = publish_dropdown.getElementsByTagName("li");
for (let publish of publishs) {
    publish.onclick = function () {
        jump("/NewsController/toPost")
    };
}
const personals = personalDropdown.getElementsByTagName("li");
personals[0].onclick = function () {
    jump("http://localhost:8080/user/personal_page")
};
personals[1].onclick = function () {
    jump("/creator");
}
personals[2].onclick = function () {
    //退出登录设置
    jump("http://localhost:8080/user/logout");
}